<?php
/**
 * 设计师剔除撤回管理
 */
namespace Beerus\Modules\DesignerRanking\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Article;
use Doraemon\model\DesignerAuth;
use Doraemon\model\DesignerRanking\DesignerRanking;
use Doraemon\model\DesignerRanking\DesignerRankingChange;
use Doraemon\model\DesignerRanking\DesignerRankingMonth;
use Doraemon\service\DesignerRanking\Ranking;
use Doraemon\tools\ActionLog;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;

class RemoveController extends Controller {
    const PAGE_SIZE = 10;

    public function list(Request $request, Content $content) {
        $list = DesignerRankingMonth::getList();
        $gridModel = new pGridDataModel($list);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableRowSelector();
                $grid->disableColumnSelector();
                $grid->disablePagination();
                $grid->disableCreateButton();
                $grid->column('id');
                $grid->column('ranking_month', '榜单号')->display(function () {
                    $format = [];
                    $format[] = "<a href='/admin/DesignerRanking/remove/list/{$this->ranking_month}'>{$this->ranking_month}</a>";
                    return $format;
                })->label('default');
                $grid->disableActions();

            });
        return $content->header('榜单剔除管理')->row($gridList);
    }

    public function rankList(
        Request $request,
        Content $content,
        $iCurRankingMonth,
        $iCurAreaCode = 0,
        $sCurMainRankingName = '',
        $sCurSubRankingName = ''
    )
    {
        Admin::script($this->setScript());
        $aRankingList = DesignerRankingChange::getMainRankingNameList($iCurRankingMonth);
        if (empty($aRankingList)) {
            $tab = '暂无被剔除的设计师～';
        } else {
            $aMainRankingList = $aRankingList ? array_column($aRankingList, 'main_ranking_name') : [];
            // 查询城市
            $aRankingCityList = DesignerRankingChange::getCityList($iCurRankingMonth);
            $aRankingAreaCodes = array_unique($aRankingCityList);
            if (empty($iCurAreaCode)) {
                $iCurAreaCode = $aRankingAreaCodes[0];
            }
            if (empty($sCurMainRankingName)) {
                $aWithAreaRankingList = DesignerRankingChange::getMainRankingNameListWithArea($iCurRankingMonth, $iCurAreaCode);
                $sCurMainRankingName = $aWithAreaRankingList[0]['main_ranking_name'];
            }
            if (empty($sCurSubRankingName)) {
                $aWithAreaRankingList = DesignerRankingChange::getSubRankingNameList($iCurRankingMonth, $iCurAreaCode, $sCurMainRankingName);
                $sCurSubRankingName = $aWithAreaRankingList[0]['sub_ranking_name'];
            }
            $aSubRankingList = [];
            if ($aMainRankingList) {
                foreach ($aRankingList as $aMainRankItem) {
                    $aSubRankingList[$aMainRankItem['main_ranking_name']] = DesignerRankingChange::getSubRankingNameList($iCurRankingMonth, $iCurAreaCode, $aMainRankItem['main_ranking_name']);
                }
            }
            $childTab = new Tab();
            foreach ($aRankingList as $aMainRanking) {
                if (empty($aSubRankingList[$aMainRanking['main_ranking_name']])) {
                    continue;
                }
                // 三级
                $thirdChild = new Tab();
                foreach ($aSubRankingList[$aMainRanking['main_ranking_name']] as $aSubRanking) {
                    // 查看该榜单下是否小于3个，小于3个则忽略展示该榜单
                    $rankingUids = DesignerRanking::getAllRankingDesignerUidsList($iCurRankingMonth, $iCurAreaCode, $sCurMainRankingName, $aSubRanking['sub_ranking_name']);
                    $removeUidCnt = DesignerRankingChange::getRemoveDesignerCnt($iCurRankingMonth, $aSubRanking['sub_ranking_name'], $iCurAreaCode, $rankingUids);
                    if ($removeUidCnt == 0) {
                        continue;
                    }
                    if (!$sCurSubRankingName) {
                        $sCurSubRankingName = $aSubRanking['sub_ranking_name'];
                    }
                    if ($aSubRanking['sub_ranking_name'] === $sCurSubRankingName) {
                        $thirdChild->add("3-{$aSubRanking['sub_ranking_name']}", $this->getList($iCurRankingMonth, $sCurSubRankingName, $sCurMainRankingName, $iCurAreaCode), true);
                    } else {
                        $thirdChild->add("3-{$aSubRanking['sub_ranking_name']}", '');
                    }
                }
                //二级
                if ($aMainRanking['main_ranking_name'] === $sCurMainRankingName) {
                    $childTab->add("2-{$aMainRanking['main_ranking_name']}", $thirdChild, true);
                } else {
                    $childTab->add("2-{$aMainRanking['main_ranking_name']}", $thirdChild);
                }
            }
            // 一级
            $tab = new Tab();
            foreach ($aRankingAreaCodes as $iAreaCode) {
                $bActive = $iAreaCode === $iCurAreaCode;
                $sCityName = Region::getNameByCode($iAreaCode);
                $tab->add("1-{$iAreaCode}-{$sCityName}", $childTab, $bActive);
            }

            Admin::html("<input type='hidden' class='rankingMonth' value='" . $iCurRankingMonth . "'>");
            Admin::html("<input type='hidden' class='subRank' value='" . $sCurSubRankingName . "'>");
            Admin::html("<input type='hidden' class='mainRank' value='" . $sCurMainRankingName . "'>");
            Admin::html("<input type='hidden' class='areaCode' value='" . $iCurAreaCode . "'>");
        }
        $header = '第'.$iCurRankingMonth.'期榜单';
        $content->row($tab);
        return $content
            ->header($header)
            ->description(' ')
            ->breadcrumb(['text' => '榜单剔除管理'], ['text' => $header]);
    }

    public function getList($iRankingMonth, $sSubRankingName, $sMainRankingName, $iAreaCode) {
        $aRemoveDesignerList = DesignerRankingChange::getRemoveDesignerList($iRankingMonth, $sMainRankingName, $sSubRankingName, $iAreaCode);
        $aDesignerList = [];
        $aUidWithInfoAssoc = [];
        if (!empty($aRemoveDesignerList)) {
            $aUids = array_column($aRemoveDesignerList, 'assoc_id');
            $aUidWithInfoAssoc = array_column($aRemoveDesignerList, null, 'assoc_id');
            $aDesignerList = DesignerRanking::getRemoveRankingDesignerListByUids($iRankingMonth, $iAreaCode, $sMainRankingName, $sSubRankingName, $aUids);
            Ranking::adminFormatList($aDesignerList, $iRankingMonth, false);
        }

        $iIsPublishRanking = DesignerRankingMonth::getDataStatus($iRankingMonth);

        $gridModel = new pGridDataModel($aDesignerList, 20, [
            'keyName' => 'designer_uid'
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($iRankingMonth, $sSubRankingName, $sMainRankingName, $iAreaCode, $aUidWithInfoAssoc, $iIsPublishRanking) {
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disablePagination();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->column('ranking_no', '排名');
            $grid->column('designer_uid', 'UID');
            $grid->column('designer_name', '设计师')->display(function() {
                $designerAuthStatusTxt = '';
                if ($this->designer_auth_status != DesignerAuth::STATUS_AUDIT_PASS_SECOND) {
                    $designerAuthStatusTxt = "<span style='color:#dd4b39'>（未认证）</span>";
                }
                return $this->designer_name . $designerAuthStatusTxt;
            });
            $grid->column('user_type', '身份');
            $grid->column('operator_name', '对接运营');
            $grid->column('ranking_article_list', '案例')->display(function () use ($iRankingMonth, $sSubRankingName, $sMainRankingName, $iAreaCode) {
                foreach ($this->ranking_article_list as $article) {
                    $articleTxt = "整屋ID：{$article['article_id']}";
                    if ($article['article_status'] != Article::STATUS_SUCCESS) {
                        $articleTxt .= "<span style='color:#dd4b39'>(" . Article::STATUS_MAP[$article['article_status']] . ")</span";
                    }
                    $img = "<a href='/admin/DesignerRanking/rank/articleCover/jump/{$iRankingMonth}/{$iAreaCode}/{$sMainRankingName}/{$sSubRankingName}/{$article['article_id']}'><img width='100' height='100' src='{$article['cover_pic']}'></a>";
                    $title = "<a href='/admin/DesignerRanking/rank/articleAudit/jump/{$iRankingMonth}/{$article['article_id']}'>{$article['title']}</a>";
                    $intro = $article['intro'];
                    $articleRet[] = implode('<br/>', [$img, $articleTxt, $title, $intro]);
                }
                return implode('<br/><br/>', $articleRet);
            });
            $grid->column('ranking_score', '推荐值');
            $grid->column('op_log', '剔除记录')->display(function () use ($aUidWithInfoAssoc) {
                return '操作人：'.Admin::user()->find($aUidWithInfoAssoc[$this->designer_uid]['admin_id'])->name.'<br>'
                    .'操作时间：'.date('Y-m-d H:i:s', $aUidWithInfoAssoc[$this->designer_uid]['add_time']);
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) use ($iRankingMonth, $iIsPublishRanking) {
                $actions->disableEdit();
                $actions->disableDelete();
                if ($this->row['ranking_status'] == Ranking::RANKING_AUDITING && $iIsPublishRanking == DesignerRankingMonth::DATA_STATUS_ABNORMAL) {
                    $actions->append('<a class=\'fa fa-trash trash-rank\' data-uid="' . $this->row["designer_uid"] . '" data-type="' . $iRankingMonth . '"  data-ranking_month ="' . $this->row['ranking_month'] . '" >撤回</a>');
                }
            });
        });
        return $listGrid->render();
    }

    /*设置scirpt
    *
    * */
    private function setScript()
    {
        return <<<SCRIPT
         $('.nav-tabs li').click(function(e){
              tabName = e.target.innerText.split('-');
              console.log(tabName);
              var rankMonth = $('.rankingMonth').val();
              if (tabName[0] == 1) {
                 var areaCode = tabName[1];
                 parent.window.location.replace('/admin/DesignerRanking/remove/list/'+rankMonth+'/'+areaCode)
              } else if (tabName[0] == 2) {
                 var areaCode = $('.areaCode').val();
                 var mainRankName = tabName[1];
                 parent.window.location.replace('/admin/DesignerRanking/remove/list/'+rankMonth+'/'+areaCode+'/'+mainRankName)
              } else {
                 var areaCode = $('.areaCode').val();
                 var mainRankName = $('.mainRank').val();
                 var subRankName = tabName[1];
                 parent.window.location.replace('/admin/DesignerRanking/remove/list/'+rankMonth+'/'+areaCode+'/'+mainRankName+'/'+subRankName)
              }
        });
       
       $('.trash-rank').unbind('click').click(function(){
            var designerUid= $(this).data('uid');
            console.log(designerUid);
            var rankingMonth = $('.rankingMonth').val();
            var areaCode = $('.areaCode').val();
            var mainRank = $('.mainRank').val();
            var subRank = $('.subRank').val();
            layer.confirm('确定要撤销踢除么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/DesignerRanking/remove/designer/'+ rankingMonth +'/' + areaCode +'/' + mainRank + '/' +subRank+'/'+designerUid+'/revoke';
                let params = {};
                $.post(url, params , function (result) {
                    console.log(result)
                    if (result.status == true) {
                        layer.msg(result.message);
                        var loadUrl = '/admin/DesignerRanking/remove/list/'+rankingMonth;
                        if (result.next_query_params != '') {
                            loadUrl += result.next_query_params;
                        }
                        console.log(loadUrl);
                        setTimeout(function () {
                            window.location.href = loadUrl;
                        }, 1000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
SCRIPT;
    }

    public function RevokeRemoveDesigner(
        Request $request,
        $iRankingMonth,
        $iAreaCode,
        $sMainRank,
        $sSubRank,
        $iDesignerUid
    ) {
        $rankingStatus = Ranking::getRankingStatus($iRankingMonth);
        if ($rankingStatus != Ranking::RANKING_AUDITING) {
            return response()->json([
                'status' => false,
                'message' => "该榜单不在审核期间，不允许撤销剔除！",
            ]);
        }
        // 通过id查设计师uid
        $data = [
            'ranking_month' => $iRankingMonth,
            'main_ranking_name' => $sMainRank,
            'sub_ranking_name' => $sSubRank,
            'area_code' => $iAreaCode,
            'assoc_type' => DesignerRankingChange::ASSOC_TYPE_REMOVE_DESIGNER,
            'assoc_id' => $iDesignerUid,
        ];
        if (!DesignerRankingChange::deleteData($data)) {
            Log::info('设计师撤销剔除失败1', $data);
            return response()->json([
                'status' => false,
                'message' => "设计师撤销剔除失败1",
            ]);
        }
        // 更新榜单数据状态
        $updateCondition = [
            'ranking_month' => $iRankingMonth,
            'main_ranking_name' => $sMainRank,
            'sub_ranking_name' => $sSubRank,
            'area_code' => $iAreaCode,
            'designer_uid' => $iDesignerUid,
        ];
        if (!DesignerRanking::update(['data_status'=>DesignerRanking::STATUS_NORMAL], $updateCondition)) {
            Log::info('设计师撤销剔除失败2', [
                'data_status'=>DesignerRanking::STATUS_NORMAL,
                'condition' => $updateCondition
            ]);
            return response()->json([
                'status' => false,
                'message' => "设计师撤销剔除失败2",
            ]);
        }
        ActionLog::log($iDesignerUid, [
            'designer_uid' => $iDesignerUid,
            'main_ranking_name' => $sMainRank,
            'sub_ranking_name' => $sSubRank,
            'area_code' => $iAreaCode,
            'admin_id' => Admin::user()->id,
            'op' => 'revoke_remove'
        ], ActionLog::BEERUS_RANKING_ACTION);
        return response()->json([
            'status' => true,
            'message' => "设计师撤销剔除成功",
            'next_query_params' => self::getNextQueryParams($iRankingMonth, $iAreaCode, $sMainRank, $sSubRank)
        ]);
    }

    public static function getNextQueryParams($iRankingMonth, $iAreaCode, $sMainRank, $sSubRank) {
        if (!DesignerRankingChange::getAreaRankingList($iRankingMonth, $iAreaCode)) {
            $aRankingCityList = DesignerRankingChange::getCityList($iRankingMonth);
            $aRankingAreaCodes = array_unique($aRankingCityList);
            $iAreaCode = $aRankingAreaCodes[0] ?? '';
        }
        if (!DesignerRankingChange::getMainRankingList($iRankingMonth, $iAreaCode, $sMainRank)) {
            $aWithAreaRankingList = DesignerRankingChange::getMainRankingNameListWithArea($iRankingMonth, $iAreaCode);
            $sMainRank = $aWithAreaRankingList[0]['main_ranking_name'] ?? '';
        }
        if (!DesignerRankingChange::getSubRankingList($iRankingMonth, $iAreaCode, $sMainRank, $sSubRank)) {
            $aWithAreaRankingList = DesignerRankingChange::getSubRankingNameList($iRankingMonth, $iAreaCode, $sMainRank);
            $sSubRank = $aWithAreaRankingList[0]['sub_ranking_name'] ?? '';
        }
        $sQueryParams = '';
        if ($iAreaCode) {
            $sQueryParams .= "/{$iAreaCode}";
        }
        if ($sMainRank) {
            $sQueryParams .= "/{$sMainRank}";
        }
        if ($sSubRank) {
            $sQueryParams .= "/{$sSubRank}";
        }
        return $sQueryParams;
    }
}
